package com.lagou.ipersistence.session.defaults;

import com.lagou.ipersistence.exceptions.PersistenceException;
import com.lagou.ipersistence.executor.Executor;
import com.lagou.ipersistence.mapping.Environment;
import com.lagou.ipersistence.session.*;
import com.lagou.ipersistence.transaction.Transaction;
import com.lagou.ipersistence.transaction.TransactionFactory;
import com.lagou.ipersistence.transaction.jdbc.JdbcTransactionFactory;

import java.sql.SQLException;

/**
 * @author Yan Jiahong
 * Created on 2020/11/7
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private Configuration configuration;
    
    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }
    
    @Override
    public SqlSession openSession() {
        return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
    }
    
    private DefaultSqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,
                                                        boolean autoCommit) {
        Transaction trx = null;
        try {
            final Environment environment = configuration.getEnvironment();
            final TransactionFactory transactionFactory = new JdbcTransactionFactory();
            trx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
            Executor executor = configuration.newExecutor(execType, trx);
            return new DefaultSqlSession(configuration, executor, autoCommit);
        } catch (Exception e) {
            closeTransaction(trx);
            throw new PersistenceException("卡其session失败, 原因: " + e, e);
        }
    }
    
    private void closeTransaction(Transaction trx) {
        if (trx != null) {
            try {
                trx.close();
            } catch (SQLException e) {
                // do nothing
            }
        }
    }
}
